//
//  NavigationHelper.m
//  ocdemo
//
//  Created by mac on 2025/10/12.
//

#import "NavigationHelper.h"
#import "AppDelegate.h"
@implementation NavigationHelper


+(UINavigationController *)topNavViewController{
    
    UIViewController *vc=[self keyWindow].rootViewController;
    return  [self findNavFromViewController:vc];
    
}
+(UITabBarController *)tabbarViewController{
    
    AppDelegate*appdelegate= (AppDelegate *)[UIApplication sharedApplication].delegate;
    return  appdelegate.tabVc;
    
}

+(UIWindow *)keyWindow{
    //iOS13+
    if(@available(iOS 13.0,*)){
        NSSet<UIScene *> *connectedScenes = [UIApplication sharedApplication].connectedScenes;
               for (UIScene *scene in connectedScenes) {
                   if ([scene isKindOfClass:[UIWindowScene class]] && scene.activationState == UISceneActivationStateForegroundActive) {
                       UIWindowScene *windowScene = (UIWindowScene *)scene;
                       for (UIWindow *window in windowScene.windows) {
                           if (window.isKeyWindow) {
                               return window;
                           }
                       }
                   }
               }
           }
    
    //iOS 13-
    return [[UIApplication sharedApplication ] keyWindow];
    
}
#pragma mark - navigationController
+(UINavigationController *)findNavFromViewController:(UIViewController * )vc{
    
    if([vc isKindOfClass:[UINavigationController class]]){
        return  (UINavigationController * ) vc;
        
    }
    if([vc isKindOfClass:[UITableViewController class]]){
        UITabBarController *tabvc=(UITabBarController *)vc;
        UIViewController *selectvc=tabvc.selectedViewController;
        
        if(selectvc){
            return  [self findNavFromViewController:selectvc];
        }
    }
    if(vc.presentedViewController){
        return [self findNavFromViewController:vc.presentedViewController];
    }
    return  vc.navigationController;
}

+(void)popViewControllerAnimated:(BOOL)animated{
    
    UINavigationController *nav=  [self topNavViewController];
    [nav popViewControllerAnimated:animated];
}
+(void)popToRootViewControllerAnimated:(BOOL)animated{
    UINavigationController *nav=  [self topNavViewController];
    [nav popToRootViewControllerAnimated:animated];
}
+(void)popToViewController:(UIViewController *)viewController animated:(BOOL)animated{
    UINavigationController *nav=  [self topNavViewController];
    [nav popToViewController:viewController animated:animated];
}
+(BOOL)canPopViewController{
    UINavigationController *nav=  [self topNavViewController];
    return  nav&&nav.viewControllers.count>1;
}
#pragma mark - tabbarController

+(void)selectTabWithIndex:(NSInteger )index{
    [[self tabbarViewController] setSelectedIndex:index];
}
@end
